package com.qdu.service.impl;

import com.qdu.entity.Userinfo;
import com.qdu.entity.Validate;
import com.qdu.mapper.ValidateMapper;
import com.qdu.service.ValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ValidateServiceImpl implements ValidateService{

	@Autowired
    private ValidateMapper validateMapper;
	@Autowired
	private JavaMailSender javaMailSender;
	
	@Override
    public void sendPasswordResetEmail(MimeMessage email){
        javaMailSender.send(email);
    }

    @Override
    public int insertNewResetRecord(Validate validate, Userinfo userinfo, String token){
        validate.setUname(userinfo.getUname());
        validate.setUemail(userinfo.getUemail());
        validate.setVtoken(token);
        validate.setCreatedate(new Date());
        return validateMapper.insert(validate);
    }

    @Override
    public Validate findUserByResetToken(String token){
        return validateMapper.selectByToken(token);
    }
    
    @Override
    public boolean sendValidateLimitation(String email, long interval){
        List<Validate> validateList = validateMapper.selectByEmail(email);
        if (validateList.isEmpty()) {
            return true;
        }
        long intervalForLastRequest = new Date().getTime() - validateList.get(0).getCreatedate().getTime();

        return intervalForLastRequest >= interval * 60 * 1000;
    }
    
    @Override
    public boolean validateLimitation(String email, long interval, String token){
    	List<Validate> validates=validateMapper.selectByEmail(email);
    	Validate validate=validateMapper.selectByToken(token);
        long intervalForLastRequest = new Date().getTime() - validate.getCreatedate().getTime();
        return intervalForLastRequest <= interval * 60 * 1000 && validate.getCreatedate().getTime()>=validates.get(0).getCreatedate().getTime();
    }

	
}
